package com.starchen.optimalselection.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starchen.optimalselection.common.service.CategoryService;
import com.starchen.optimalselection.common.mapper.CategoryMapper;
import com.starchen.optimalselection.common.model.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> getTreeList() {
        List<Category> allCategoryList = categoryMapper.selectList(null);

        List<Category> categoryList = allCategoryList.stream().filter(category -> category.getParentId() == 0).map(category -> {
            category.setChildren(getCategoryChildred(allCategoryList,category));
            return category;
        }).sorted(Comparator.comparing(Category::getSort)).collect(Collectors.toList());
        return categoryList;
    }

    private List<Category> getCategoryChildred(List<Category> allEntity, Category rootCategory){
        List<Category> categoryList = allEntity.stream().filter(category -> category.getParentId() == rootCategory.getId()).map(category -> {
            category.setChildren(getCategoryChildred(allEntity,category));
            return category;
        }).sorted(Comparator.comparing(Category::getSort)).collect(Collectors.toList());
        return  categoryList;
    }

    @Override
    public Long[] getCategoryPath(Long cateId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = getParentPath(cateId, paths);

        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> getParentPath(Long cateId,List<Long> paths){
        //1、收集当前节点id
        paths.add(cateId);
        Category byId = categoryMapper.selectById(cateId);
        if(byId.getParentId()!=0){
            getParentPath(byId.getParentId(),paths);
        }
        return paths;
    }

    @Override
    public List<Category> getOneLevelCategory() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",0);
        List<Category> categoryList = categoryMapper.selectList(queryWrapper);
        return categoryList;
    }

}